/*
 * @Author: tianjunguo
 * @Date: 2019-08-27 10:39:11
 * @Last Modified by: tianjunguo
 * @Last Modified time: 2020-01-08 15:08:16
 * 资产配置报告
 */

<template>
    <section class="assetReport">

        <div class="questionWrap">
            <div class="listSection">
            <div class="listSectionRound" v-for="(questionNow,i) in questionNows" :key="i">
                <!-- 选择题时 -->
                <div class="question" :num="questionNow.questionNo" v-if="questionNow.list.length && questionIndex == questionNow.questionNo && questionIndex != 6">
                    <p class="topic">{{questionNow.questionContent}}</p>
                    <ul class="list">
                        <!-- 循环答案 -->
                        <li v-for="(l , index) in questionNow.list" @click="radioAction(index,questionNow.questionNo,questionNow)" :key="index">
                            <span class="txt">{{l.answerContent}}</span>
                            <!-- <radio :radioName="questionNow.radioName" :hasChecked="questionNow.answerResult == index + 1" :ref="getRadioRef(index)"></radio> -->
                            <i class="iconfont radioModelchecked" v-if="questionNow.answerResult == index + 1">&#xe673;</i>
                            <i class="iconfont radioModel" v-else>&#xe672;</i>
                        </li>
                    </ul>
                </div>
                <!-- 多选题 -->
                <div class="question" :num="questionNow.questionNo" v-if="questionNow.list.length && questionIndex == questionNow.questionNo && questionIndex == 6">
                    <p class="topic">{{questionNow.questionContent}}</p>
                    <ul class="list">
                        <!-- 循环答案 -->
                        <li v-for="(l , index) in questionNow.list" @click="radioActionMore(index,questionNow.answerResult,questionNow)" :key="index">
                            <span class="txt">{{l.answerContent}}</span>
                            <i class="iconfont radioModelchecked" v-if="testAnswer(questionNow.answerResult,index)">&#xe675;</i>
                            <i class="iconfont radioModel" v-else>&#xe674;</i>
                        </li>
                    </ul>
                </div>

                <!-- 填空题时 -->
                <div class="question tkQuestion" :num="questionNow.questionNo" v-if="!questionNow.list.length && questionIndex == questionNow.questionNo">

                    <ul class="quesUl">
                        <li class='quesLi'>
                            <p class="topic">{{splitQuestion(questionNow.questionContent)[0]}}</p>
                            <div class="formSection">
                                <ul class="list">
                                    <li class="item hasUnit">
                                        <div class="unit">万元</div>
                                        <input class="ipt" type="tel" placeholder="" v-model="questionNow.answerResult.split(',')[0]" @input="fillIn($event,i,questionNow.answerResult,1)" maxlength="10" />
                                    </li>
                                </ul>
                            </div>
                        </li>
                    </ul>

                    <ul class="quesUl" v-if="splitQuestion(questionNow.questionContent)[1]">
                        <li class='quesLi'>
                            <p class="topic">{{splitQuestion(questionNow.questionContent)[1]}}</p>
                            <div class="formSection">
                                <ul class="list">
                                    <li class="item hasUnit">
                                        <div class="unit">万美元</div>
                                        <input class="ipt" type="tel" placeholder="" v-model="questionNow.answerResult.split(',')[1]" @input="fillIn($event,i,questionNow.answerResult,2)" maxlength="10" />
                                    </li>
                                </ul>
                                
                            </div>
                        </li>
                    </ul>
                </div>
                </div>
                <!-- 进度条 -->
                <div class="progressbarWrap">
                     <div class="progressbar" :style="'width:'+questionIndex/questionNum * 100+'%'"></div>
                </div>
                <div class="control">
                    <span class="prev" @click="clickPrev" :style="visibilityPrev">上一题</span>
                    <span class="questionNum">({{questionIndex}}/{{questionNum}})</span>
                    <span class="next" @click="clickNext" :style="visibilityNext">下一题</span>
                </div>
                <!-- 当前题目解释 -->
                <discription v-if="questionNow.questionNo == 3" discriptionTxt="稳定收入的含义为月收入是家庭总月度开销的2倍"></discription>
                <!-- <div class="nextStep">
                    下一步
                </div> -->
                
            </div>


        </div>

        <!-- 提交 -->
        <mt-button @click="goNext()" class="bottom" size="large" ref="nextBtn" v-show="btnShow">提交</mt-button>

    </section>

</template>

<script>


export default {
    name: "question",
    components:{
        // radio
    },
    // 父组件需要传递到子组件得值，
    props:{
        // 问卷id，新建不需要，编辑时键值ids,
        ids:{
            type:String,
            default:""
        }
    },
    data() {
        return {
            visibilityPrev:"visibility:hidden",
            visibilityNext:"visibility:visible",
          //存放接口拿到的所有题目
            questionList: null,
            questionIsChange:false,//是否变更答案
            questionFirstChange:false,//是否已经变更答案
            //当前题目
            questionNow: {
                list: []
            },
            btnShow:true,
            questionNows:[],
            questionIndex:1,//当前第几题
            //题目个数
            questionNum: 0,

            //答案数组
            answerList: [] ,

            //第4道填空题的答案
            tkAnswer_1: '',
            //选填题的答案
            tkAnswer_2: '',

            //控制按钮点击
            isClick: false,

            //控制下一步按钮展示隐藏
            btnShow: false, 

            //接口请求回来的字典值保存
            descArr: {      
                lifeTermDic: null, //生命周期
                riskTypeDic: null, //风险偏好
                assetClassifyDic: null, //资产分类
                assetTypeDic: null, //资产类别
            },
            thirdQuestions:[],//第三道题选项，
        };
    },
    created() {
        //请求字典
        this.getDic();

        //请求题目
        this.getQuestion();
    },

    mounted(){


        if(this.isWechat) {
            window.addEventListener('scroll', this.handleScroll, true);  // 监听（绑定）滚轮滚动事件
        };
    },

    updated (){
       
    },

    watch: {
      
    },
    methods: {
        goNext(){
            this.setAnswer()
        },
        setAnswer(){
            this.questionNows.forEach((element,i,arr) => {
                //答案中有选择的这项，删除选项
                this.answerList[i].questionNo = element.questionNo;//问题序号
                this.answerList[i].questionTitle = element.questionContent;//问题标题
                this.answerList[i].answerContent = element.answerResult;//答案

            })

            //接口成功后跳转3
            this.$parent.changeToSteps(3)
            

            console.log(this.answerList)
        },
        fillIn(ev,index,answer,valueNum){
            console.log(ev.target.value)
            console.log(index)
            let fillAnswerArr = [];
            let answerArr = answer.split(',');
            
            // 如何判断答案中没有该项值，没有的话答案中添加变为可选，
            if(answerArr[0] != ev.target.value && valueNum == 1){//答案中不存在点击的项，将该项加到数组中,作为答案
                answerArr[0] = ev.target.value
            }else if(answerArr[1] != ev.target.value && valueNum == 2){
                //答案中有选择的这项，删除选项，
                answerArr[1] = ev.target.value
            }
            //将选择或者取消选择的题目重新记录
            this.questionNows[this.questionIndex*1 - 1].answerResult = answerArr.toString();
            this.questionIsChange = this.isSameArr(this.questionList,this.questionNows);//判断是否答案变更
            console.log(this.questionNows[this.questionIndex*1 - 1])
        },
        testAnswer(answer,index){
            let moreCheck = false;
            let arrAnswer = answer.split(',');
            // questionNow.answerResult.split(',')[] == index + 1
            arrAnswer.forEach(element => {
                if(element == index + 1){
                    moreCheck = true;
                }
                
            });
            return moreCheck;
        },
        // 点击上一题
        clickPrev(){
            this.btnShow = false;
            this.questionIndex-=1;
            // 下一页显示
            this.visibilityNext = "visibility:visible";
            // 如果是第一页，上一页隐藏
            if(this.questionIndex == 1){
                this.visibilityPrev = "visibility:hidden";
            }
            // 记录下一题时答案是否变更，已变更则视为变更
            this.questionFirstChange = this.questionIsChange;
            //下一题，先判断当前页面上题目有没有选
            // this.questionNows[this.questionIndex-1].radioName = 'radio_' + this.questionIndex;
        },
        // 点击下一题
        clickNext(){
            //加不少于100万元的判断 。如果填写小于100万，则点击下一题或点“提交”时提示“可配置资产量级金额不得少于100万元”
            if(this.questionIndex == 4){
                if(this.questionNows[this.questionIndex*1 - 1].answerResult.split(",")[0] < 100 || this.questionNows[this.questionIndex*1 - 1].answerResult.split(",")[1] < 100){
                    this.$toast("可配置资产量级金额不得少于100万元");
                    return false;
                }

            }
            this.questionIndex+=1;
            // 点击下一页上一页显示，
            this.visibilityPrev = "visibility:visible";
            // 如果是最后一页，则下一页隐藏
            if(this.questionIndex == this.questionNows.length){
                this.visibilityNext = "visibility:hidden";
                this.btnShow = true
            }
            // 记录上一题时答案是否变更，已变更则视为变更
            this.questionFirstChange = this.questionIsChange;
             //下一题，先判断当前页面上题目有没有选
            // this.questionNows[this.questionIndex-1].radioName = 'radio_' + this.questionIndex;
        },
        getDic(){
            this.$axiosHttp.http({
                name:'获取字典',
                url: apiUrl.getCustomerAssetDictionaryApi,
                data:["1001", "1002","1003", "1004"], 
            }, (res) => {
               /* 1000是与否
                1001生命周期阶段
                1002客户风险承受能力
                1003资产分类
                1004资产类别
                1005项目类型
                1006细分策略
                1007家庭未来现金流稳定性*/

                //1001生命周期阶段
                this.descArr.lifeTermDic=res.data.data[1001];
                this.descArr.riskTypeDic = res.data.data[1002];  //风险承受能力字典值
                this.descArr.assetClassifyDic = res.data.data[1003]; //资产分类
                this.descArr.assetTypeDic = res.data.data[1004]; //资产类别
                
            })

        },
        // 判断两个数组是否相等
        isSameArr(arr,arr2){
            var same = true;
            for (var i = 0; i < arr.length; i++) {
                if (arr2[i].answerResult != arr[i].answerResult) {
                    same = false;
                    break;
                }
            }
            return same;
        },
         //获取问题和答案
        getQuestion(){
            var that = this;

            this.$axiosHttp.http({
                name:'请求问卷题目答案',
                url: apiUrl.selectQuesAndAnsApi,
                params: {
                    id:  this.ids, //资产配置id ，新增时可不传，编辑时必传，用于回显
                }
            }, (res) => {

                //所有问题及答案
                this.questionList = this.$utils.objDeepCopy(res.data.data);
                this.questionNows = res.data.data;
                //题目数量
                this.questionNum = this.questionList.length;
                this.thirdQuestions = this.questionNows[2].list;
                //用户的答案数组默认生成
                var aArr = [];
                // $.each( that.questionList, function(i, el){
                that.questionList.forEach(function(el,i,item){
                
                    if( el.questionNo == 4 ){
                        //填空题时，元转成万元，有答案
                        //
                        if( !!el.answerResult ){
                            var answer = el.answerResult.split(','),
                                newAnswer = [];
                            answer.forEach( (l, i, a) => {
                                //从元转为万元
                                newAnswer.push( that.$utils.toThousand( Number(l) ) ) ; 
                            })    
                            //newAnswer再转成字符串
                            newAnswer = newAnswer.join(',');  
                        }
                        aArr.push( {
                            questionNo: el.questionNo,
                            answerContent: el.answerResult ?  newAnswer : null //如果是编辑，可能是已经有了答案的
                        })  
                                        
                    }
                    else{
                        aArr.push( {
                            questionNo: el.questionNo,
                            answerContent: el.answerResult ?  el.answerResult : null //如果是编辑，可能是已经有了答案的
                        })
                    }
                    
                })
                this.answerList = aArr;

                //展示第一道题
                this.questionNow = this.questionList[0];
                // this.questionNow.radioName = 'radio_1' ;
                //根据1题答案设置3题选项
                this.fileterthirdAnswers()

                //回显答案
                // this.setAnswer(0);

            })
        }, 
         //点击整行时
        radioAction( index ,questionNo,questionNow){
            this.questionNows[questionNo - 1].answerResult = index + 1;
            //记录问卷是否修改
            this.questionIsChange = this.isSameArr(this.questionList,this.questionNows);
            console.log(this.isSameArr(this.questionList,this.questionNows))
//             this.$emit('isChange',this.questionIsChange)//传递答案是否变更
//             -若Q1选择已婚，则显示选项：
            // A.我与配偶均有稳定的收入。B.我与配偶其中一人有稳定的收入。C.我与配偶均没有稳定的收入，或均已退休。
            // 现金流稳定性判断：若选择A则未来现金流稳定性为稳定这一档；若选择B则未来现金流稳定性为一般，若选C则未来现金流稳定性为不稳定。
            // -若Q1选择单身，则显示选项：
            // A.我本人有稳定的收入。B.我本人目前暂无稳定的收入。
            if(questionNo == 1){
                this.fileterthirdAnswers()
            }
            // console.log(this.questionIsChange)
        },
        //根据第一道题筛选第三题答案
        fileterthirdAnswers(){
            if(this.questionNows[0].answerResult == 1){
                this.questionNows[2].list = this.thirdQuestions.slice(0,3)
            }else if(this.questionNows[0].answerResult == 2){
                this.questionNows[2].list = this.thirdQuestions.slice(-2)
            }
        },
        // 多选选择整行时操作,index题目点击的下标
        radioActionMore(index,answer){
            debugger;
            let answerArr = answer.split(',');
            // 如何判断答案中没有该项值，没有的话答案中添加变为可选，
            if(this.findSameValue(answerArr,index) == -1){//答案中不存在点击的项，将该项加到数组中,作为答案
                answerArr.push(index + 1)
            }else{
                //答案中有选择的这项，删除选项，
                // answerArr.splice(index,1)
                answerArr = answerArr.filter(function(item){
                    return item != index+1
                })
            }
            //将选择或者取消选择的题目重新记录
            this.questionNows[this.questionIndex*1 - 1].answerResult = answerArr.toString();
            //记录问卷是否修改
            this.questionIsChange = this.isSameArr(this.questionList,this.questionNows);
            console.log(this.isSameArr(this.questionList,this.questionNows))
            // answer = answerArr.toString();

        },
        transformAnswer(index,answer,i){
            let answerArr = answer.split(',');
            //将选择或者取消选择的题目重新记录
            this.questionNows[this.questionIndex*1 - 1].answerResult = answerArr.toString();
            if(i == 1){//第一项值
                return answerArr[0]
            }else if(i == 2){
                return answerArr[1]
            }

        },
        //查找多选题点击项值是否存在，不存在返回-1，存在返回存在的下标
        findSameValue(answerArr,index){
            let value = -1;
            answerArr.forEach((element,i,arr) => {
                //答案中有选择的这项，删除选项
                if(element == index+1 ){
                    value = i;
                }
            })
            return value;
        },
        //拆分填空题题目
        splitQuestion( question){
            if( !!question ){
                return question.split(',');
            }
            else{
                return []
            }
        },


       

       
    }
};
</script>
<style lang="less" scoped>
    .rem(@name,@px){
        @name:unit(@px / 20,rem)
    }
    .listSection{
        padding: 0 .75rem;
        margin-top: 0.5rem;
        background: #fff;
    }
    .question{
        .topic{
            font-size: .75rem;
            padding: .6rem 0;
            color: #FF6500;
            letter-spacing: 0;
            border-bottom: 1px solid #E7E7E7;
        }
        .list{
            height: 11.7rem;
            overflow-y: scroll;
            li{
                .radioBox{
                    float: right;
                }
                padding: .775rem 0;
                border-bottom: 1px solid #E7E7E7;
                .txt{
                    font-size: .65rem;
                    color:#545861;
                }
                .iconfont{
                    float: right;
                    margin-right: 1px;
                }
                .radioModelchecked{
                    color: #FF6500;
                }

            }
        }
    }
    .progressbarWrap{
        margin-top: .775rem;
        width: 100%;
        height:.25rem;
        background-color: #E7E7E7;
        border-radius: .125rem;
        .progressbar{
            width:10%;
            height: 100%;
            background-color: #FF6500;
            border-radius: .125rem;
        }
    }
    .control{
        display: flex;
        justify-content: space-between;
        margin-top: .7rem;
        font-size: .75rem;
        span{
            display: flex;
        }
        .questionNum{
            color:#666687;
        }
        .next{
            color: #FF6500;
        }
    }
    .tkQuestion{
        height: 14rem;
        .list{
            height: auto;
            li{
                border-bottom:none;
                height: 3.2rem;
                background: transparent;
                .unit{
                    float: right;
                    line-height: 2.33rem;
                }
                .ipt{
                    width: 7.5rem;
                    float: right;
                    border-bottom: 0.5px solid #91959E;
                    font-size: .8rem;
                    text-align: right;
                    background: transparent;
                }
            }
        }
    }
</style>